<template>
  <div class="shop-rent-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      size="default"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="店铺" prop="shopId">
            <el-select 
              v-model="formData.shopId" 
              placeholder="请选择店铺" 
              style="width: 100%"
              filterable
              clearable
            >
              <el-option
                v-for="shop in shopList"
                :key="shop.id"
                :label="shop.shopName"
                :value="shop.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租金月份" prop="rentMonth">
            <el-date-picker
              v-model="formData.rentMonth"
              type="month"
              placeholder="请选择租金月份"
              style="width: 100%"
              format="YYYY-MM"
              value-format="YYYY-MM"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="租赁开始日期" prop="leaseStartDate">
            <el-date-picker
              v-model="formData.leaseStartDate"
              type="date"
              placeholder="请选择租赁开始日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租赁结束日期" prop="leaseEndDate">
            <el-date-picker
              v-model="formData.leaseEndDate"
              type="date"
              placeholder="请选择租赁结束日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="租金金额" prop="rentAmount">
            <el-input-number
              v-model="formData.rentAmount"
              placeholder="请输入租金金额"
              :min="0"
              :max="100000"
              :precision="2"
              style="width: 100%"
            />
            <template #suffix>元</template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否月度租金" prop="isMonthlyRent">
            <el-radio-group v-model="formData.isMonthlyRent" @change="handleMonthlyRentChange">
              <el-radio :value="1">是</el-radio>
              <el-radio :value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 批量生成月度租金选项 -->
      <el-row v-if="formData.isMonthlyRent === 1" :gutter="20">
        <el-col :span="24">
          <el-form-item label="批量生成选项">
            <el-checkbox v-model="formData.batchGenerate" @change="handleBatchGenerateChange">
              批量生成月度租金记录
            </el-checkbox>
            <div class="batch-tip">
              <el-text type="info" size="small">
                选择后将自动按月份生成从租赁开始到结束的所有租金记录
              </el-text>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 批量生成设置 -->
      <div v-if="formData.isMonthlyRent === 1 && formData.batchGenerate" class="batch-settings">
        <el-card shadow="never" class="batch-card">
          <template #header>
            <div class="card-header">
              <el-icon><Calendar /></el-icon>
              <span>批量生成设置</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="租期开始日期" prop="batchStartDate">
                <el-date-picker
                  v-model="formData.batchStartDate"
                  type="date"
                  placeholder="请选择租期开始日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  @change="calculateBatchRecords"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租期结束日期" prop="batchEndDate">
                <el-date-picker
                  v-model="formData.batchEndDate"
                  type="date"
                  placeholder="请选择租期结束日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  @change="calculateBatchRecords"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="月租金金额" prop="batchRentAmount">
                <el-input-number
                  v-model="formData.batchRentAmount"
                  placeholder="请输入月租金金额"
                  :min="0"
                  :max="100000"
                  :precision="2"
                  style="width: 100%"
                />
                <template #suffix>元</template>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生成记录数">
                <el-input
                  :value="batchRecordCount"
                  readonly
                  style="width: 100%"
                />
                <template #suffix>条</template>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 预览信息 -->
          <div v-if="batchRecordCount > 0" class="batch-preview">
            <el-alert
              :title="`将生成 ${batchRecordCount} 条月度租金记录`"
              type="info"
              :closable="false"
              show-icon
            >
              <template #default>
                <div class="preview-content">
                  <p>租期：{{ formData.batchStartDate }} 至 {{ formData.batchEndDate }}</p>
                  <p>月租金：¥{{ formData.batchRentAmount?.toFixed(2) || '0.00' }}</p>
                  <p>总金额：¥{{ (batchRecordCount * (formData.batchRentAmount || 0)).toFixed(2) }}</p>
                </div>
              </template>
            </el-alert>
          </div>
        </el-card>
      </div>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="到期日期" prop="dueDate">
            <el-date-picker
              v-model="formData.dueDate"
              type="date"
              placeholder="请选择到期日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付状态" prop="paymentStatus">
            <el-radio-group v-model="formData.paymentStatus">
              <el-radio :value="0">未支付</el-radio>
              <el-radio :value="1">已支付</el-radio>
              <el-radio :value="2">逾期</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="formData.paymentStatus === 1">
        <el-col :span="12">
          <el-form-item label="支付日期" prop="paymentDate">
            <el-date-picker
              v-model="formData.paymentDate"
              type="date"
              placeholder="请选择支付日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="formData.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
              <el-option label="现金" value="CASH" />
              <el-option label="银行转账" value="BANK_TRANSFER" />
              <el-option label="支付宝" value="ALIPAY" />
              <el-option label="微信支付" value="WECHAT" />
              <el-option label="其他" value="OTHER" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="formData.paymentStatus === 1">
        <el-col :span="12">
          <el-form-item label="收据号" prop="receiptNumber">
            <el-input
              v-model="formData.receiptNumber"
              placeholder="请输入收据号"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit" 
        :loading="submitting"
        :disabled="submitting"
      >
        {{ mode === 'add' ? '新增' : '保存' }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Calendar } from '@element-plus/icons-vue'
import { shopRentApi } from '@/api/shop-rent'
import { shopApi } from '@/api/shop'
import { shopOwnerApi } from '@/api/shop-owner'
import type { ShopRentRecordVO, ShopVO, ShopOwnerVO } from '../types'
import type { ShopRentFormData } from '@/api/shop-rent'

// Props
interface Props {
  rentId?: number | null
  mode: 'add' | 'edit'
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  success: []
  cancel: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const lastSubmitTime = ref(0)
const shopList = ref<ShopVO[]>([])
const ownerList = ref<ShopOwnerVO[]>([])

// 批量生成相关计算属性
const batchRecordCount = computed(() => {
  if (!formData.batchStartDate || !formData.batchEndDate) return 0
  
  const startDate = new Date(formData.batchStartDate)
  const endDate = new Date(formData.batchEndDate)
  
  if (startDate >= endDate) return 0
  
  // 计算月份差
  const yearDiff = endDate.getFullYear() - startDate.getFullYear()
  const monthDiff = endDate.getMonth() - startDate.getMonth()
  
  return yearDiff * 12 + monthDiff + 1
})

// 表单数据
const formData = reactive({
  shopId: null as number | null,
  rentAmount: null as number | null,
  rentMonth: '',
  isMonthlyRent: 1,
  leaseStartDate: '',
  leaseEndDate: '',
  rentPeriod: '',
  rentStartDate: '',
  rentEndDate: '',
  paymentStatus: 0,
  paymentMethod: '',
  invoiceNumber: '',
  remark: '',
  // 批量生成相关字段
  batchGenerate: false,
  batchStartDate: '',
  batchEndDate: '',
  batchRentAmount: null as number | null
})

// 表单验证规则
const formRules: FormRules = {
  shopId: [
    { required: true, message: '请选择店铺', trigger: 'change' }
  ],
  rentAmount: [
    { required: true, message: '请输入租金金额', trigger: 'blur' }
  ],
  rentMonth: [
    { required: true, message: '请选择租金月份', trigger: 'change' }
  ],
  leaseStartDate: [
    { required: true, message: '请选择租赁开始日期', trigger: 'change' }
  ],
  leaseEndDate: [
    { required: true, message: '请选择租赁结束日期', trigger: 'change' }
  ],
  paymentStatus: [
    { required: true, message: '请选择支付状态', trigger: 'change' }
  ],
  // 批量生成验证规则
  batchStartDate: [
    { 
      required: true, 
      message: '请选择租期开始日期', 
      trigger: 'change',
      validator: (rule: any, value: string, callback: Function) => {
        if (formData.batchGenerate && !value) {
          callback(new Error('请选择租期开始日期'))
        } else {
          callback()
        }
      }
    }
  ],
  batchEndDate: [
    { 
      required: true, 
      message: '请选择租期结束日期', 
      trigger: 'change',
      validator: (rule: any, value: string, callback: Function) => {
        if (formData.batchGenerate && !value) {
          callback(new Error('请选择租期结束日期'))
        } else if (formData.batchGenerate && formData.batchStartDate && value <= formData.batchStartDate) {
          callback(new Error('租期结束日期必须大于开始日期'))
        } else {
          callback()
        }
      }
    }
  ],
  batchRentAmount: [
    { 
      required: true, 
      message: '请输入月租金金额', 
      trigger: 'blur',
      validator: (rule: any, value: number, callback: Function) => {
        if (formData.batchGenerate && (!value || value <= 0)) {
          callback(new Error('请输入有效的月租金金额'))
        } else {
          callback()
        }
      }
    }
  ],
  paymentDate: [
    { required: true, message: '请选择支付日期', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

// 计算属性
const isEdit = computed(() => props.mode === 'edit')

// 生命周期
onMounted(() => {
  loadShopList()
  loadOwnerList()
  if (isEdit.value && props.rentId) {
    loadRentInfo()
  }
})

// 监听支付状态变化
watch(() => formData.paymentStatus, (newStatus) => {
  if (newStatus === 0) {
    formData.paymentDate = ''
    formData.paymentMethod = ''
    formData.receiptNumber = ''
  } else if (newStatus === 1) {
    formData.paymentDate = new Date().toISOString().split('T')[0]
  }
})

// 方法
const loadShopList = async () => {
  try {
    const response = await shopApi.getShopPage({
      current: 1,
      size: 100 // 限制在100以内
    })
    
    if (response.code === 200) {
      shopList.value = response.data.records
    } else {
      ElMessage.error(response.message || '加载店铺列表失败')
    }
  } catch (error) {
    ElMessage.error('加载店铺列表失败')
    console.error('加载店铺列表失败:', error)
  }
}

const loadOwnerList = async () => {
  try {
    const response = await shopOwnerApi.getShopOwnerPage({
      current: 1,
      size: 100 // 限制在100以内
    })
    
    if (response.code === 200) {
      ownerList.value = response.data.records
    } else {
      ElMessage.error(response.message || '加载业主列表失败')
    }
  } catch (error) {
    ElMessage.error('加载业主列表失败')
    console.error('加载业主列表失败:', error)
  }
}

const loadRentInfo = async () => {
  if (!props.rentId) return
  
  try {
    const response = await shopRentApi.getRentRecordDetail(props.rentId)
    
    if (response.data.code === 200) {
      const rent = response.data.data
      Object.assign(formData, {
        shopId: rent.shopId,
        ownerId: rent.ownerId,
        rentAmount: rent.rentAmount,
        rentPeriod: rent.rentPeriod,
        rentStartDate: rent.rentStartDate,
        rentEndDate: rent.rentEndDate,
        paymentStatus: rent.paymentStatus,
        paymentMethod: rent.paymentMethod,
        invoiceNumber: rent.invoiceNumber,
        remark: rent.remark
      })
    } else {
      ElMessage.error(response.data.message || '加载租金信息失败')
    }
  } catch (error) {
    ElMessage.error('加载租金信息失败')
    console.error('加载租金信息失败:', error)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  // 防重复提交检查
  if (submitting.value) {
    ElMessage.warning('正在提交中，请勿重复操作')
    return
  }
  
  // 时间戳防重复提交检查（1秒内不允许重复提交）
  const currentTime = Date.now()
  if (currentTime - lastSubmitTime.value < 1000) {
    ElMessage.warning('提交过于频繁，请稍后再试')
    return
  }
  lastSubmitTime.value = currentTime
  
  try {
    await formRef.value.validate()
    
    // 设置提交状态，防止重复提交
    submitting.value = true
    
    console.log('开始提交表单，防重复提交已启用')
    
    // 判断是否为批量生成
    if (formData.batchGenerate && formData.isMonthlyRent === 1) {
      console.log('执行批量生成逻辑，单次API调用')
      
      // 使用后端批量生成逻辑，避免重复提交
      const batchRecord = {
        shopId: formData.shopId,
        rentAmount: formData.batchRentAmount,
        isMonthlyRent: 1,
        leaseStartDate: formData.batchStartDate,
        leaseEndDate: formData.batchEndDate,
        // 为满足后端验证，添加必要的字段
        rentMonth: formData.batchStartDate ? formData.batchStartDate.substring(0, 7) : '',
        rentPeriod: formData.batchStartDate ? formData.batchStartDate.substring(0, 7) : '',
        rentStartDate: formData.batchStartDate,
        rentEndDate: formData.batchEndDate,
        paymentStatus: 0,
        paymentMethod: formData.paymentMethod,
        invoiceNumber: formData.invoiceNumber,
        remark: formData.remark
      }
      
      // 验证必需字段
      if (!batchRecord.rentMonth) {
        ElMessage.error('请选择租期开始日期')
        return
      }
      if (!batchRecord.rentStartDate) {
        ElMessage.error('请选择租期开始日期')
        return
      }
      if (!batchRecord.rentEndDate) {
        ElMessage.error('请选择租期结束日期')
        return
      }
      
      console.log('批量生成参数:', batchRecord)
      
      // 调用后端批量生成API（单次调用）
      const response = await shopRentApi.createRentRecord(batchRecord)
      
      console.log('批量生成API响应:', response)
      
      if (response.code === 200) {
        const result = response.data
        ElMessage.success(`批量创建成功！成功创建 ${result.successCount} 条记录${result.failCount > 0 ? `，失败 ${result.failCount} 条` : ''}`)
        emit('success')
      } else {
        ElMessage.error(response.message || '批量创建失败')
      }
    } else {
      // 单条记录创建
      const rentRecord = {
        shopId: formData.shopId,
        rentAmount: formData.rentAmount,
        rentMonth: formData.rentMonth,
        isMonthlyRent: formData.isMonthlyRent,
        leaseStartDate: formData.leaseStartDate,
        leaseEndDate: formData.leaseEndDate,
        rentPeriod: formData.rentPeriod,
        rentStartDate: formData.rentStartDate,
        rentEndDate: formData.rentEndDate,
        paymentStatus: formData.paymentStatus,
        paymentMethod: formData.paymentMethod,
        invoiceNumber: formData.invoiceNumber,
        remark: formData.remark
      }
      
      const response = await shopRentApi.createRentRecord(rentRecord)
      
      if (response.code === 200) {
        ElMessage.success('创建租金记录成功')
        emit('success')
      } else {
        ElMessage.error(response.message || '创建租金记录失败')
      }
    }
  } catch (error) {
    if (error !== false) {
      ElMessage.error('提交失败')
      console.error('提交失败:', error)
    }
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 处理月度租金选择变化
const handleMonthlyRentChange = (value: number) => {
  if (value === 0) {
    // 如果不是月度租金，关闭批量生成
    formData.batchGenerate = false
  }
}

// 处理批量生成选择变化
const handleBatchGenerateChange = (value: boolean) => {
  if (value) {
    // 如果选择批量生成，设置默认值
    if (!formData.batchStartDate) {
      formData.batchStartDate = formData.leaseStartDate || new Date().toISOString().split('T')[0]
    }
    if (!formData.batchEndDate) {
      formData.batchEndDate = formData.leaseEndDate || new Date().toISOString().split('T')[0]
    }
    if (!formData.batchRentAmount) {
      formData.batchRentAmount = formData.rentAmount
    }
  }
}

// 计算批量记录数量
const calculateBatchRecords = () => {
  // 触发计算属性重新计算
  batchRecordCount.value
}

// 生成月度租金记录数据
const generateMonthlyRentRecords = () => {
  if (!formData.batchStartDate || !formData.batchEndDate || !formData.batchRentAmount) {
    return []
  }
  
  const records = []
  const startDate = new Date(formData.batchStartDate)
  const endDate = new Date(formData.batchEndDate)
  
  let currentDate = new Date(startDate)
  
  while (currentDate <= endDate) {
    const year = currentDate.getFullYear()
    const month = currentDate.getMonth() + 1
    const rentMonth = `${year}-${month.toString().padStart(2, '0')}`
    
    // 计算当月第一天和最后一天
    const monthStart = new Date(year, month - 1, 1)
    const monthEnd = new Date(year, month, 0)
    
    records.push({
      shopId: formData.shopId,
      rentAmount: formData.batchRentAmount,
      rentMonth: rentMonth,
      isMonthlyRent: 1,
      leaseStartDate: monthStart.toISOString().split('T')[0],
      leaseEndDate: monthEnd.toISOString().split('T')[0],
      rentPeriod: rentMonth,
      rentStartDate: monthStart.toISOString().split('T')[0],
      rentEndDate: monthEnd.toISOString().split('T')[0],
      paymentStatus: 0,
      paymentMethod: '',
      invoiceNumber: '',
      remark: `月度租金 - ${rentMonth}`
    })
    
    // 移动到下个月
    currentDate.setMonth(currentDate.getMonth() + 1)
  }
  
  return records
}
</script>

<style scoped>
.shop-rent-form {
  padding: 20px;
}

.batch-tip {
  margin-top: 8px;
}

.batch-settings {
  margin-top: 20px;
}

.batch-card {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.batch-preview {
  margin-top: 16px;
}

.preview-content {
  margin-top: 8px;
}

.preview-content p {
  margin: 4px 0;
  font-size: 14px;
  color: #606266;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.form-actions .el-button {
  margin: 0 8px;
  min-width: 100px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__suffix) {
  color: #909399;
  font-size: 14px;
}
</style>
